#! /usr/bin/env python
# coding: utf-8

"""
一个代码提交到Gerrit的python脚本
"""

import os
import subprocess
import sys

def upload(path):
    global GIT

    GIT = 'git'
    git_dir = os.path.join(path, '.git')

    branch_proc = subprocess.Popen([GIT, '--git-dir=%s' % git_dir,
        'symbolic-ref', 'HEAD'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    REPO_REV = branch_proc.stdout.read().strip().split('/')[2]
    branch_proc.stdout.close()

    branch_proc.stderr.read()
    branch_proc.stderr.close()

    if branch_proc.wait() != 0:
        print >>sys.stderr, 'fatal: %s has no current branch' % gitdir
    else:
        subprocess.call('git --git-dir=%s push origin HEAD:refs/for/%s' %
                (git_dir, REPO_REV), shell=True)

def main(args):
    for project in args[1:]:
        if os.path.isdir(project):
            if os.path.isdir(os.path.join(project, '.git')):
                upload(project)
            else:
                print >>sys.stderr, '%s do not have .git dir ? failed !' % project
        else:
            print >>sys.stderr, '%s is not a project!' % project

    print 'All is done!'

def usage():
    print 'Usage: python upload.py [projects...]'
    sys.exit(-1)

if __name__ == '__main__':

    if not os.path.isdir('.repo'):
        print >>sys.stderr, 'Please exec this script in root of android !'
        exit(-1)

    if len(sys.argv) < 2:
        usage()

    main(sys.argv)

